import requests
import logging
from typing import Optional, List, Dict, Callable, Set
from pathlib import Path
import json
from utils.network_scanner import NetworkScanner

class ServerManager:
    """Ollama服务器管理器"""
    def __init__(self, config_file: str = "config/servers.json"):
        self.logger = logging.getLogger(__name__)
        self.config_file = Path(config_file)
        self.current_server: Optional[Dict] = None
        self.servers: List[Dict] = []
        self.scanner = NetworkScanner()
        self._load_servers()
    
    def _load_servers(self):
        """加载服务器配置"""
        if self.config_file.exists():
            try:
                self.servers = json.loads(self.config_file.read_text())
            except Exception as e:
                self.logger.error(f"加载服务器配置失败: {str(e)}")
                self.servers = []
    
    def _save_servers(self):
        """保存服务器配置"""
        self.config_file.parent.mkdir(parents=True, exist_ok=True)
        try:
            self.config_file.write_text(json.dumps(self.servers, indent=2))
        except Exception as e:
            self.logger.error(f"保存服务器配置失败: {str(e)}")
    
    def scan_network(self, 
                    progress_callback: Optional[Callable] = None,
                    progress_bar: Optional[Callable] = None) -> List[Dict]:
        """扫描网络查找服务器"""
        try:
            # 使用 NetworkScanner 扫描
            found_ips = self.scanner.scan_network(progress_callback, progress_bar)
            found_servers = []
            
            # 获取服务器信息
            for ip in found_ips:
                try:
                    response = requests.get(
                        f"http://{ip}:{self.scanner.port}/api/version",
                        timeout=0.5
                    )
                    if response.status_code == 200:
                        server = {
                            "host": ip,
                            "port": self.scanner.port,
                            "version": response.json().get("version", "unknown")
                        }
                        found_servers.append(server)
                        self.logger.info(f"发现服务器: {ip}")
                except Exception as e:
                    self.logger.error(f"获取服务器信息失败 {ip}: {str(e)}")
            
            return found_servers
        
        except Exception as e:
            self.logger.error(f"扫描网络失败: {str(e)}")
            return []
    
    def add_network(self, network: str) -> bool:
        """添加自定义网段"""
        return self.scanner.add_network(network)
    
    def remove_network(self, network: str) -> bool:
        """移除自定义网段"""
        return self.scanner.remove_network(network)
    
    def get_networks(self) -> Set[str]:
        """获取所有自定义网段"""
        return self.scanner.get_networks()
    
    def add_server(self, host: str, port: int = 11434) -> bool:
        """添加服务器"""
        try:
            # 测试连接
            response = requests.get(
                f"http://{host}:{port}/api/version",
                timeout=2
            )
            if response.status_code == 200:
                server = {
                    "host": host,
                    "port": port,
                    "version": response.json().get("version", "unknown")
                }
                if server not in self.servers:
                    self.servers.append(server)
                    self._save_servers()
                return True
        except Exception as e:
            self.logger.error(f"添加服务器失败: {str(e)}")
        return False
    
    def connect(self, host: str, port: int = 11434) -> bool:
        """连接到服务器"""
        try:
            response = requests.get(
                f"http://{host}:{port}/api/version",
                timeout=2
            )
            if response.status_code == 200:
                self.current_server = {
                    "host": host,
                    "port": port,
                    "version": response.json().get("version", "unknown")
                }
                return True
        except Exception as e:
            self.logger.error(f"连接服务器失败: {str(e)}")
            self.current_server = None
        return False
    
    def get_current_server(self) -> Optional[Dict]:
        """获取当前连接的服务器"""
        return self.current_server
    
    def get_servers(self) -> List[Dict]:
        """获取所有已知服务器"""
        return self.servers 